//
//  AMPhotoManager.swift
//  YCCamera
//
//  Created by Billy on 2024/5/16.
//

import Photos
import UIKit

@objcMembers
public class AMPhotoManager : NSObject {
    
    private let sessionQueue = DispatchQueue(label: "com.yc.photo.sessionQueue")
    
    public class func options(key: String, ascending: Bool) -> PHFetchOptions {
        let options = PHFetchOptions()
        options.sortDescriptors = [NSSortDescriptor(key: key, ascending: ascending)]
        return options
    }
    
    public class func requestAsset(identifier: String) -> PHAsset? {
        let options = PHFetchOptions()
        let result = PHAsset.fetchAssets(withLocalIdentifiers: [identifier], options: options)
        return result.firstObject
    }
    
    public class func asyncRequestImage(identifier: String, targetSize: CGSize, completion: @escaping (UIImage?) -> Void) {
        guard let asset = requestAsset(identifier: identifier) else {
            completion(nil)
            return
        }
        
        requestImage(asset: asset, targetSize: targetSize, synchronous: false, completion: completion)
    }
    
    public class func syncRequestImage(asset: PHAsset, targetSize: CGSize, completion: @escaping (UIImage?) -> Void) { 
        requestImage(asset: asset, targetSize: targetSize, synchronous: true, completion: completion)
    }
    
    public class func syncRequestImage(asset: PHAsset, targetSize: CGSize) -> UIImage? {
        var repImage: UIImage?
        
        syncRequestImage(asset: asset, targetSize: targetSize) { image in
            repImage = image
        }
        return repImage
    }
    
    public class func requestImage(asset: PHAsset, targetSize: CGSize, synchronous: Bool, completion: @escaping(UIImage?) -> Void) {
        let options = PHImageRequestOptions()
        // 是否同步执行
        options.isSynchronous = synchronous
        options.resizeMode = .fast
        
        // 获取缩略图
        PHImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFill, options: options) { image, info in
            completion(image)
        }
    }
    
    public class func getAlbumPhotos() -> [String] {
        var photos = [String]()
        
        // 获取最近项目相册
        let recentAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil)
        recentAlbums.enumerateObjects { collection, _, _ in
            let collection = collection
            
            let options = PHFetchOptions()
            options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
            
            let assetsResult = PHAsset.fetchAssets(in: collection, options: options)
            assetsResult.enumerateObjects { object, _, _ in
                let asset = object 
                photos.append(asset.localIdentifier)
            }
        }
        
        return photos
    }
    
//    public class func fetchPhotoForMonth(completion: @escaping ())
    
    public class func fetchSimilarArray(completion: @escaping ([Any]) -> Void) {
        var outputArray: [[PHAsset]] = []
        
        // 筛选条件
        let momentOptions = options(key: "startDate", ascending: false)
        let assetsOptions = options(key: "creationDate", ascending: false)
        
        let collectionList = PHCollectionList.fetchCollectionLists(with: .momentList, subtype: .momentListCluster, options: momentOptions)
        
        print("~~~~~~~~collectionList的个数为\(collectionList.count)")
        
        // 创建一个并发队列
        let photoQueue = DispatchQueue(label: "com.yc.photo.photoQueue", attributes: .concurrent)
        
        // 使用 DispatchGroup 来跟踪所有任务的完成情况
        let group = DispatchGroup()
        
        collectionList.enumerateObjects { (obj, idx, stop) in
            
            group.enter()
            
            // 提交任务到并发队列中
            photoQueue.async {
                // 创建一个时刻存放数组
                let moment = obj
                
                // 获取时刻里面的asset合集
                let result = PHAssetCollection.fetchMoments(inMomentList: moment, options: momentOptions)
                result.enumerateObjects { obj, idx, stop in
                    let collection = obj
                    
                    // 获取每日asset合集
                    let daysResults = PHAsset.fetchAssets(in: collection, options: assetsOptions)
                    
                    // 每天的照片数要大于1才进行相似度判断
                    if daysResults.count > 1 {
                        var assets = [PHAsset]()
                        
                        // 筛选媒体类型
                        daysResults.enumerateObjects { (obj, idx, stop) in
                            // 获取图片类型
                            if obj.mediaType == .image {
                                assets.append(obj)
                            }
                        }
                        
                        let disArray = AMSimilarityManager.similarityGroup(assets)
                        if disArray.count > 0 {
                            outputArray.append(disArray)
                            print("......扫描到的相似照片\(outputArray.count)张")
                        }
                    }
                }
                
                group.leave()
            }
        }
        
        // 所有任务完成后调用
        group.notify(queue: .main) {
            completion(outputArray)
        }
    }
}

public extension AMPhotoManager {
    
    
}

